<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Inziu Iosevka Slab SC:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate o">
<meta property="og:type" content="article">
<meta property="og:title" content="Numpy Note">
<meta property="og:url" content="http://idmk.oschina.io/2017/08/28/numpy-note/index.html">
<meta property="og:site_name" content="苦舟">
<meta property="og:description" content="NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate o">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-09-06T14:42:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Numpy Note">
<meta name="twitter:description" content="NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate o">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idmk.oschina.io/2017/08/28/numpy-note/"/>





  <title>Numpy Note | 苦舟</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苦舟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无涯，吾将上下求索。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idmk.oschina.io/2017/08/28/numpy-note/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="东木金">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苦舟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Numpy Note</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-28T14:42:33+08:00">
                2017-08-28
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.</p>
<a id="more"></a>
<h2 id="ndarray-数据结构"><a href="#ndarray-数据结构" class="headerlink" title="ndarray 数据结构"></a>ndarray 数据结构</h2><p>NumPy 的核心功能是 “ndarray”( 即 n-dimensional array，多维数组 ) 数据结构。这是一个表示多维度、同质并且固定大小的数组对象。而由一个与此数组相关系的数据类型对象来描述其数组元素的数据格式 ( 例如其字符组顺序、在内存中占用的字符组数量、整数或者浮点数等等 )。</p>
<h2 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h2><h3 id="创建数组"><a href="#创建数组" class="headerlink" title="创建数组"></a>创建数组</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>x</div><div class="line">array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.arange(<span class="number">10</span>)  <span class="comment"># 類似 Python 的 range, 但是回傳 array</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>y</div><div class="line">array([<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> numpy.random <span class="keyword">import</span> rand</div><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> numpy.linalg <span class="keyword">import</span> solve, inv</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c = rand(<span class="number">3</span>, <span class="number">3</span>)</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>solve(a, b)</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>inv(a)</div></pre></td></tr></table></figure>
<h3 id="基本运算"><a href="#基本运算" class="headerlink" title="基本运算"></a>基本运算</h3><p>与标量做加减乘除。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>a = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">6</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>b = np.linspace(<span class="number">0</span>, <span class="number">2</span>, <span class="number">4</span>)  <span class="comment"># 建立一個 array, 在 0 與 2 的範圍之間讓 4 個點等分</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c = a - b</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c</div><div class="line">array([ <span class="number">1.</span>        ,  <span class="number">1.33333333</span>,  <span class="number">1.66666667</span>,  <span class="number">4.</span>        ])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>a**<span class="number">2</span></div><div class="line">array([ <span class="number">1</span>,  <span class="number">4</span>,  <span class="number">9</span>, <span class="number">36</span>])</div></pre></td></tr></table></figure></p>
<h3 id="全域方法"><a href="#全域方法" class="headerlink" title="全域方法"></a>全域方法</h3><p>即对矩阵 / 向量中各个元素作用的方法<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>a = np.linspace(-np.pi, np.pi, <span class="number">100</span>)</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>b = np.sin(a)</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c = np.cos(a)</div></pre></td></tr></table></figure></p>
<h3 id="线性代数"><a href="#线性代数" class="headerlink" title="线性代数"></a>线性代数</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> numpy.random <span class="keyword">import</span> rand</div><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> numpy.linalg <span class="keyword">import</span> solve, inv</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>a = np.array([[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">3</span>, <span class="number">4</span>, <span class="number">6.7</span>], [<span class="number">5</span>, <span class="number">9.0</span>, <span class="number">5</span>]])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>a.T</div><div class="line">array([[ <span class="number">1.</span> ,  <span class="number">3.</span> ,  <span class="number">5.</span> ],</div><div class="line">       [ <span class="number">2.</span> ,  <span class="number">4.</span> ,  <span class="number">9.</span> ],</div><div class="line">       [ <span class="number">3.</span> ,  <span class="number">6.7</span>,  <span class="number">5.</span> ]])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>a <span class="comment">#inv(a)</span></div><div class="line">array([[<span class="number">-2.27683616</span>,  <span class="number">0.96045198</span>,  <span class="number">0.07909605</span>],</div><div class="line">       [ <span class="number">1.04519774</span>, <span class="number">-0.56497175</span>,  <span class="number">0.1299435</span> ],</div><div class="line">       [ <span class="number">0.39548023</span>,  <span class="number">0.05649718</span>, <span class="number">-0.11299435</span>]])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>b =  np.array([<span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>solve(a, b)  <span class="comment"># 解方程式 ax = b</span></div><div class="line">array([<span class="number">-4.83050847</span>,  <span class="number">2.13559322</span>,  <span class="number">1.18644068</span>])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c = rand(<span class="number">3</span>, <span class="number">3</span>)  <span class="comment"># 建立一個 3x3 隨機矩陣</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>c</div><div class="line">array([[  <span class="number">3.98732789</span>,   <span class="number">2.47702609</span>,   <span class="number">4.71167924</span>],</div><div class="line">       [  <span class="number">9.24410671</span>,   <span class="number">5.5240412</span> ,  <span class="number">10.6468792</span> ],</div><div class="line">       [ <span class="number">10.38136661</span>,   <span class="number">8.44968437</span>,  <span class="number">15.17639591</span>]])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>np.dot(a, c)  <span class="comment"># 矩陣相乘</span></div><div class="line">array([[  <span class="number">53.61964114</span>,   <span class="number">38.8741616</span> ,   <span class="number">71.53462537</span>],</div><div class="line">       [ <span class="number">118.4935668</span> ,   <span class="number">86.14012835</span>,  <span class="number">158.40440712</span>],</div><div class="line">       [ <span class="number">155.04043289</span>,  <span class="number">104.3499231</span> ,  <span class="number">195.26228855</span>]])</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>np.dot(a, inv(a))</div><div class="line">array([[  <span class="number">1.00000000e+00</span>,   <span class="number">0.00000000e+00</span>,   <span class="number">0.00000000e+00</span>],</div><div class="line">       [  <span class="number">0.00000000e+00</span>,   <span class="number">1.00000000e+00</span>,   <span class="number">0.00000000e+00</span>],</div><div class="line">       [  <span class="number">0.00000000e+00</span>,   <span class="number">0.00000000e+00</span>,   <span class="number">1.00000000e+00</span>]])</div></pre></td></tr></table></figure>
<h3 id="ndarray-ndarray"><a href="#ndarray-ndarray" class="headerlink" title="ndarray * ndarray"></a><code>ndarray * ndarray</code></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; import numpy as np</div><div class="line">&gt;&gt;&gt; a = np.array([[1 ,2], [3, 4]])</div><div class="line">&gt;&gt;&gt; a</div><div class="line">array([[1, 2],</div><div class="line">       [3, 4]])</div><div class="line">&gt;&gt;&gt; b = np.array([1,2])</div><div class="line">&gt;&gt;&gt; a *b</div><div class="line">array([[1, 4],</div><div class="line">       [3, 8]])</div><div class="line">&gt;&gt;&gt; tb = b.T</div><div class="line">&gt;&gt;&gt; a * tb</div><div class="line">array([[1, 4],</div><div class="line">       [3, 8]])</div></pre></td></tr></table></figure>
<h2 id="arrays-vs-matrices"><a href="#arrays-vs-matrices" class="headerlink" title="arrays vs matrices"></a>arrays vs matrices</h2><ol>
<li>What are the advantages and disadvantages of each?</li>
<li>From what I’ve seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them?</li>
<li>Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are indeed lots of matrices, but also lots of vectors (arrays).</li>
</ol>
<p>Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.<br>The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a<em>b is their matrix product.<br>On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python &gt;= 3.5.<br>Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.<br>In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise<br>To obtain the result of matrix multiplication, you use np.dot (or @ in Python &gt;= 3.5, as shown above).<br>The <strong> operator also works.<br>Since a is a matrix, `a</strong>2<code>returns the matrix product</code>a</em>a<code>. Since c is an ndarray,</code>c**2` returns an ndarray with each component squared element-wise.<br>There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).</p>
<p>The main advantage of numpy arrays is that they are more general than 2-dimensional matrices.<br>What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work – you have to learn matrix object operations, and ndarray operations.<br><strong>Writing a program that uses both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don’t expect.</strong><br>In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.<br>If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python &gt;= 3.5), then I think NumPy arrays are definitely the way to go.<br>PS. Of course, you really don’t have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).</p>
<h2 id="matrix"><a href="#matrix" class="headerlink" title="matrix"></a>matrix</h2><h3 id="tolist"><a href="#tolist" class="headerlink" title="tolist"></a>tolist</h3><p><strong>保持多层结构</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; x = np.matrix(np.arange(12).reshape((3,4))); x</div><div class="line">matrix([[ 0,  1,  2,  3],</div><div class="line">        [ 4,  5,  6,  7],</div><div class="line">        [ 8,  9, 10, 11]])</div><div class="line">&gt;&gt;&gt; x.tolist()</div><div class="line">[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]</div></pre></td></tr></table></figure></p>
<p><strong>扁化</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; x = np.matrix(np.arange(12).reshape((3,4))); x</div><div class="line">matrix([[ 0,  1,  2,  3],</div><div class="line">        [ 4,  5,  6,  7],</div><div class="line">        [ 8,  9, 10, 11]])</div><div class="line">&gt;&gt;&gt; x.flatten()</div><div class="line">matrix([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])</div><div class="line">&gt;&gt;&gt; x.flatten().getA()</div><div class="line">array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])</div><div class="line">&gt;&gt;&gt; x.flatten().getA()[0].tolist()</div><div class="line">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]</div></pre></td></tr></table></figure></p>
<h2 id="其他遇到过的不会使用的函数"><a href="#其他遇到过的不会使用的函数" class="headerlink" title="其他遇到过的不会使用的函数"></a>其他遇到过的不会使用的函数</h2><h3 id="numpy-split"><a href="#numpy-split" class="headerlink" title="numpy.split"></a><code>numpy.split</code></h3><p><code>numpy.split(ary, indices_or_sections, axis=0)</code><br>    Parameters:<br>        ary : ndarray<br>            Array to be divided into sub-arrays.<br>        indices_or_sections : int or 1-D array<br>            If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.<br>            If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in<br>                ary[:2]<br>                ary[2:3]<br>                ary[3:]<br>            If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.<br>        axis : int, optional<br>            The axis along which to split, default is 0.<br>    Returns:<br>        sub-arrays : list of ndarrays<br>            A list of sub-arrays.<br>    Raises:<br>        ValueError<br>            If indices_or_sections is given as an integer, but a split does not result in equal division.</p>
<h3 id="numpy-nonzero"><a href="#numpy-nonzero" class="headerlink" title="numpy.nonzero"></a><code>numpy.nonzero</code></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; x = np.array([[1,0,0], [0,2,0], [1,1,0]])</div><div class="line">&gt;&gt;&gt; x</div><div class="line">array([[1, 0, 0],</div><div class="line">       [0, 2, 0],</div><div class="line">       [1, 1, 0]])</div><div class="line">&gt;&gt;&gt; np.nonzero(x)</div><div class="line">(array([0, 1, 2, 2], dtype=int64), array([0, 1, 0, 1], dtype=int64))</div><div class="line">&gt;&gt;&gt; nonzero_idx = _</div><div class="line">&gt;&gt;&gt; x[nonzero_idx]</div><div class="line">array([1, 2, 1, 1])</div></pre></td></tr></table></figure>
<p>to find the indices of an array, where a condition is True.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.array([[1,2,3],[4,5,6],[7,8,9]])</div><div class="line">&gt;&gt;&gt; ltidx = np.nonzero(a &lt; 3); ltidx</div><div class="line">(array([0, 0], dtype=int64), array([0, 1], dtype=int64))</div><div class="line">&gt;&gt;&gt; a[ltidx] = -1; a</div><div class="line">array([[-1, -1,  3],</div><div class="line">       [ 4,  5,  6],</div><div class="line">       [ 7,  8,  9]])</div></pre></td></tr></table></figure></p>
<h3 id="unique"><a href="#unique" class="headerlink" title="unique"></a>unique</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; np.unique(iris_y)</div><div class="line">array([0, 1, 2])</div></pre></td></tr></table></figure>
<h2 id="Numpy-arrays"><a href="#Numpy-arrays" class="headerlink" title="Numpy arrays"></a>Numpy arrays</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">a = np.arange(<span class="number">1000</span>)</div><div class="line">a = np.array([<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</div><div class="line">a.ndim</div><div class="line">a.shape</div><div class="line">b = np.arange(<span class="number">1</span>, <span class="number">9</span>, <span class="number">2</span>) <span class="comment"># start, end (exclusive), step</span></div><div class="line">c = np.linspace(<span class="number">0</span>, <span class="number">1</span>, <span class="number">6</span>)</div><div class="line">d = np.linspace(<span class="number">0</span>, <span class="number">1</span>, <span class="number">5</span>, endpoint=<span class="keyword">False</span>)</div><div class="line">d = np.diag(np.arange(<span class="number">1</span>, <span class="number">5</span>))</div></pre></td></tr></table></figure>
<h3 id="random-numbers"><a href="#random-numbers" class="headerlink" title="random numbers"></a>random numbers</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">a = np.random.rand(<span class="number">4</span>) <span class="comment"># uniform in [0, 1]</span></div><div class="line">b = np.random.rand(<span class="number">4</span>, <span class="number">3</span>)</div><div class="line">c = np.random.randn(<span class="number">4</span>, <span class="number">3</span>) <span class="comment"># Gaussian</span></div></pre></td></tr></table></figure>
<h3 id="Basic-data-types"><a href="#Basic-data-types" class="headerlink" title="Basic data types"></a>Basic data types</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.array([1, 2, 3])</div><div class="line">&gt;&gt;&gt; a.dtype</div><div class="line">dtype(&apos;int32&apos;)</div><div class="line"></div><div class="line">&gt;&gt;&gt; b = np.array([1., 2., 3.])</div><div class="line">&gt;&gt;&gt; b.dtype</div><div class="line">dtype(&apos;float64&apos;)</div></pre></td></tr></table></figure>
<p>Different data-types allow us to store data more compactly in memory, but most of the time we simply work with ﬂ oating point numbers. Note that, in the example above, NumPy auto-detects the data-type from the input.</p>
<p>You can explicitly specify which data-type you want:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; c = np.array([1, 2, 3], dtype=float)</div><div class="line">&gt;&gt;&gt; c.dtype</div><div class="line">dtype(1float641)</div></pre></td></tr></table></figure></p>
<p>The default data type is ﬂ oating point:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.ones((3, 3))</div><div class="line">&gt;&gt;&gt; a.dtype</div><div class="line">dtype(&apos;float64&apos;)</div></pre></td></tr></table></figure></p>
<h4 id="There-are-also-other-types"><a href="#There-are-also-other-types" class="headerlink" title="There are also other types:"></a>There are also other types:</h4><p>Complex, Bool, Strings, int32, int64, uint32, uint64</p>
<h2 id="Basic-visualization"><a href="#Basic-visualization" class="headerlink" title="Basic visualization"></a>Basic visualization</h2><p>Start by launching IPython;<br>enable interactive plots – <code>&gt;&gt;&gt; %matplotlib</code></p>
<p>Matplotlib is a 2D plotting package. We can import its functions as below:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; import matplotlib.pyplot as plt # the tidy way</div></pre></td></tr></table></figure></p>
<p>And then use (note that you have to use show explicitly if you have not enabled interactive plots with %matplotlib):<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; plt.plot(x, y) # line plot</div><div class="line">&gt;&gt;&gt; plt.show() # &lt;-- shows the plot (not needed with interactive plots)</div></pre></td></tr></table></figure></p>
<p>Or, if you have enabled interactive plots with %matplotlib:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; plot(x, y) # line plot</div></pre></td></tr></table></figure></p>
<p>2D arrays – hot<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; image = np.random.rand(30, 30)</div><div class="line">&gt;&gt;&gt; plt.imshow(image, cmap=plt.cm.hot)</div><div class="line">&gt;&gt;&gt; plt.colorbar()</div><div class="line">&lt;matplotlib.colorbar.Colorbar instance at ...&gt;</div><div class="line">&gt;&gt;&gt; plt.show()</div></pre></td></tr></table></figure></p>
<p>2D arrays – gray<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; image = np.random.rand(30, 30)</div><div class="line">&gt;&gt;&gt; plt.imshow(image, cmap=plt.cm.gray)</div><div class="line">&gt;&gt;&gt; plt.colorbar()</div><div class="line">&lt;matplotlib.colorbar.Colorbar instance at ...&gt;</div><div class="line">&gt;&gt;&gt; plt.show()</div></pre></td></tr></table></figure></p>
<h2 id="Fancy-indexing"><a href="#Fancy-indexing" class="headerlink" title="Fancy indexing"></a>Fancy indexing</h2><p>Numpy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This method is called fancy indexing. It creates copies not views.</p>
<h3 id="Using-boolean-masks"><a href="#Using-boolean-masks" class="headerlink" title="Using boolean masks"></a>Using boolean masks</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; np.random.seed(3)</div><div class="line">&gt;&gt;&gt; a = np.random.random_integers(0, 20, 15)</div><div class="line">&gt;&gt;&gt; a</div><div class="line">array([10, 3,	8,	0, 19, 10, 11,	9, 10,	6,	0, 20, 12,	7, 14])</div><div class="line">&gt;&gt;&gt; (a % 3 == 0)</div><div class="line">array([False, True, False, True, False, False, False, True, False, True, True, False, True, False, False], dtype=bool)</div><div class="line">&gt;&gt;&gt; mask = (a % 3 == 0)</div><div class="line">&gt;&gt;&gt; extract_from_a = a[mask] # or, a[a%3==0]</div><div class="line">&gt;&gt;&gt; extract_from_a	# extract a sub-array with the mask</div><div class="line">array([ 3,	0,	9,	6,	0, 12])</div></pre></td></tr></table></figure>
<p>Indexing with a mask can be very useful to assign a new value to a sub-array:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a[a % 3 == 0] = -1 &gt;&gt;&gt; a</div><div class="line">array([10, -1,	8, -1, 19, 10, 11, -1, 10, -1, -1, 20, -1,	7, 14])</div></pre></td></tr></table></figure></p>
<p>Indexing with an array of integers<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.arange(0, 100, 10)</div><div class="line">&gt;&gt;&gt; a</div><div class="line">array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])</div></pre></td></tr></table></figure></p>
<p>Indexing can be done with an array of integers, where the same index is repeated several time:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list</div><div class="line">array([20, 30, 20, 40, 20])</div><div class="line">&gt;&gt;&gt; a[[9, 7]] = -100</div><div class="line">&gt;&gt;&gt; a</div><div class="line">array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100])</div></pre></td></tr></table></figure></p>
<p>When a new array is created by indexing with an array of integers, the new array has the same shape than the array of integers:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; idx = np.array([[3, 4], [9, 7]])</div><div class="line">&gt;&gt;&gt; a[idx]</div><div class="line">array([[  30,   40],</div><div class="line">       [-100, -100]])</div></pre></td></tr></table></figure></p>
<h2 id="Numerical-operations-on-arrays"><a href="#Numerical-operations-on-arrays" class="headerlink" title="Numerical operations on arrays"></a>Numerical operations on arrays</h2><p>Array-wise comparisons:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.array([1, 2, 3, 4])</div><div class="line">&gt;&gt;&gt; b = np.array([4, 2, 2, 4])</div><div class="line">&gt;&gt;&gt; c = np. array([1, 2, 3, 4])</div><div class="line">&gt;&gt;&gt; np.array_equal(a, b)</div><div class="line">False</div><div class="line">&gt;&gt;&gt; np.array_equal(a, c)</div><div class="line">True</div></pre></td></tr></table></figure></p>
<p>Logical operations:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.array([1, 1, 0, 0], dtype=bool)</div><div class="line">&gt;&gt;&gt; b = np.array([1, 0, 1, 0], dtype=bool)</div><div class="line">&gt;&gt;&gt; np.logical_or(a, b)</div><div class="line">array([ True, True, True, False], dtype=bool)</div><div class="line">&gt;&gt;&gt; np.logical_and(a, b)</div><div class="line">array([ True, False, False, False], dtype=bool)</div></pre></td></tr></table></figure></p>
<p>Transcendental functions:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; a = np.arange(5)</div><div class="line">&gt;&gt;&gt; np.sin(a)</div><div class="line">array([ 0.	,	0.84147098,	0.90929743,	0.14112001, -0.7568025 ])</div><div class="line">&gt;&gt;&gt; np.log(a)</div><div class="line">array([	-inf, 0.	,	0.69314718,	1.09861229,	1.38629436])</div><div class="line">&gt;&gt;&gt; np.exp(a)</div><div class="line">array([ 1.	,	2.71828183,	7.3890561 ,	20.08553692,	54.59815003])</div></pre></td></tr></table></figure></p>
<p>The transposition is a view</p>
<h2 id="Linear-algebra"><a href="#Linear-algebra" class="headerlink" title="Linear algebra"></a>Linear algebra</h2><p>The sub-module <a href="http://docs.scipy.org/doc/scipy/reference/linalg.html#module-scipy.linalg" target="_blank" rel="external">numpy.linalg</a> implements basic linear algebra, such as solving linear systems, singular value decomposition, etc. However, it is not guaranteed to be compiled using efficient routines, and thus we recommend the use of scipy.linalg, as detailed in section Linear algebra operations: <code>scipy.linalg</code></p>
<h2 id="Sort"><a href="#Sort" class="headerlink" title="Sort"></a>Sort</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; x = np.array([1, 3, 2])</div><div class="line">&gt;&gt;&gt; x.min()</div><div class="line">1</div><div class="line">&gt;&gt;&gt; x.max()</div><div class="line">3</div><div class="line">&gt;&gt;&gt; x.argmin() # index of minimum 0</div><div class="line">&gt;&gt;&gt; x.argmax() # index of maximum 1</div></pre></td></tr></table></figure>
<h2 id="Statistics"><a href="#Statistics" class="headerlink" title="Statistics"></a>Statistics</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; x = np.array([1, 2, 3, 1])</div><div class="line">&gt;&gt;&gt; y = np.array([[1, 2, 3], [5, 6, 1]])</div><div class="line">&gt;&gt;&gt; x.mean()</div><div class="line">1.75</div><div class="line">&gt;&gt;&gt; np.median(x)</div><div class="line">1.5</div><div class="line">&gt;&gt;&gt; np.median(y, axis=-1) # last axis</div><div class="line">array([ 2.,	5.])</div><div class="line">&gt;&gt;&gt; x.std()	# full population standard dev.</div><div class="line">0.82915619758884995</div></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/28/Tree-Based-Regression/" rel="next" title="Tree Based Regression（树回归）">
                <i class="fa fa-chevron-left"></i> Tree Based Regression（树回归）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/28/K-means-Clustering/" rel="prev" title="K-Means Clustering">
                K-Means Clustering <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="东木金" />
          <p class="site-author-name" itemprop="name">东木金</p>
           
              <p class="site-description motion-element" itemprop="description">正在学习机器学习，希望能变得很强！</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">42</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bdmk" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:catcherchan94@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#ndarray-数据结构"><span class="nav-number">1.</span> <span class="nav-text">ndarray 数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#语法"><span class="nav-number">2.</span> <span class="nav-text">语法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建数组"><span class="nav-number">2.1.</span> <span class="nav-text">创建数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基本运算"><span class="nav-number">2.2.</span> <span class="nav-text">基本运算</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#全域方法"><span class="nav-number">2.3.</span> <span class="nav-text">全域方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线性代数"><span class="nav-number">2.4.</span> <span class="nav-text">线性代数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ndarray-ndarray"><span class="nav-number">2.5.</span> <span class="nav-text">ndarray * ndarray</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#arrays-vs-matrices"><span class="nav-number">3.</span> <span class="nav-text">arrays vs matrices</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#matrix"><span class="nav-number">4.</span> <span class="nav-text">matrix</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#tolist"><span class="nav-number">4.1.</span> <span class="nav-text">tolist</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他遇到过的不会使用的函数"><span class="nav-number">5.</span> <span class="nav-text">其他遇到过的不会使用的函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#numpy-split"><span class="nav-number">5.1.</span> <span class="nav-text">numpy.split</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#numpy-nonzero"><span class="nav-number">5.2.</span> <span class="nav-text">numpy.nonzero</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unique"><span class="nav-number">5.3.</span> <span class="nav-text">unique</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Numpy-arrays"><span class="nav-number">6.</span> <span class="nav-text">Numpy arrays</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#random-numbers"><span class="nav-number">6.1.</span> <span class="nav-text">random numbers</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Basic-data-types"><span class="nav-number">6.2.</span> <span class="nav-text">Basic data types</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#There-are-also-other-types"><span class="nav-number">6.2.1.</span> <span class="nav-text">There are also other types:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Basic-visualization"><span class="nav-number">7.</span> <span class="nav-text">Basic visualization</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Fancy-indexing"><span class="nav-number">8.</span> <span class="nav-text">Fancy indexing</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Using-boolean-masks"><span class="nav-number">8.1.</span> <span class="nav-text">Using boolean masks</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Numerical-operations-on-arrays"><span class="nav-number">9.</span> <span class="nav-text">Numerical operations on arrays</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Linear-algebra"><span class="nav-number">10.</span> <span class="nav-text">Linear algebra</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Sort"><span class="nav-number">11.</span> <span class="nav-text">Sort</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Statistics"><span class="nav-number">12.</span> <span class="nav-text">Statistics</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">东木金</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
